package com.example.remotecontrol.ui.scenes

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.StarBorder
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.remotecontrol.data.model.Scene
import kotlinx.coroutines.launch

/**
 * 场景管理界面
 */
@Composable
fun ScenesScreen(
    viewModel: ScenesViewModel = hiltViewModel()
) {
    val scenes by viewModel.scenes.collectAsState()
    val favoriteScenes by viewModel.favoriteScenes.collectAsState()
    val isExecuting by viewModel.isExecutingScene.collectAsState()
    
    val snackbarHostState = remember { SnackbarHostState() }
    val coroutineScope = rememberCoroutineScope()
    
    var selectedTabIndex by remember { mutableStateOf(0) }
    val tabs = listOf("所有场景", "收藏场景")
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("场景") }
            )
        },
        floatingActionButton = {
            FloatingActionButton(
                onClick = { /* 跳转到添加场景界面 */ }
            ) {
                Icon(Icons.Filled.Add, contentDescription = "添加场景")
            }
        },
        snackbarHost = { SnackbarHost(snackbarHostState) }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
        ) {
            // 标签页
            TabRow(selectedTabIndex = selectedTabIndex) {
                tabs.forEachIndexed { index, title ->
                    Tab(
                        selected = selectedTabIndex == index,
                        onClick = { selectedTabIndex = index },
                        text = { Text(title) }
                    )
                }
            }
            
            // 场景列表
            when (selectedTabIndex) {
                0 -> SceneList(
                    scenes = scenes,
                    isExecuting = isExecuting,
                    onSceneClick = { scene ->
                        coroutineScope.launch {
                            viewModel.executeScene(scene.id)
                            snackbarHostState.showSnackbar("正在执行场景: ${scene.name}")
                        }
                    },
                    onFavoriteToggle = { scene ->
                        viewModel.toggleFavorite(scene.id)
                    },
                    onEditClick = { /* 跳转到编辑场景界面 */ },
                    onDeleteClick = { scene ->
                        viewModel.deleteScene(scene.id)
                        coroutineScope.launch {
                            snackbarHostState.showSnackbar("场景已删除")
                        }
                    }
                )
                1 -> SceneList(
                    scenes = favoriteScenes,
                    isExecuting = isExecuting,
                    onSceneClick = { scene ->
                        coroutineScope.launch {
                            viewModel.executeScene(scene.id)
                            snackbarHostState.showSnackbar("正在执行场景: ${scene.name}")
                        }
                    },
                    onFavoriteToggle = { scene ->
                        viewModel.toggleFavorite(scene.id)
                    },
                    onEditClick = { /* 跳转到编辑场景界面 */ },
                    onDeleteClick = { scene ->
                        viewModel.deleteScene(scene.id)
                        coroutineScope.launch {
                            snackbarHostState.showSnackbar("场景已删除")
                        }
                    }
                )
            }
        }
    }
}

/**
 * 场景列表
 */
@Composable
fun SceneList(
    scenes: List<Scene>,
    isExecuting: Boolean,
    onSceneClick: (Scene) -> Unit,
    onFavoriteToggle: (Scene) -> Unit,
    onEditClick: (Scene) -> Unit,
    onDeleteClick: (Scene) -> Unit
) {
    if (scenes.isEmpty()) {
        Column(
            modifier = Modifier.fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Text(
                text = "还没有场景",
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = "点击右下角的 + 按钮添加场景",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    } else {
        LazyColumn(
            contentPadding = PaddingValues(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            items(scenes) { scene ->
                SceneCard(
                    scene = scene,
                    isExecuting = isExecuting,
                    onClick = { onSceneClick(scene) },
                    onFavoriteToggle = { onFavoriteToggle(scene) },
                    onEditClick = { onEditClick(scene) },
                    onDeleteClick = { onDeleteClick(scene) }
                )
            }
        }
    }
}

/**
 * 场景卡片
 */
@Composable
fun SceneCard(
    scene: Scene,
    isExecuting: Boolean,
    onClick: () -> Unit,
    onFavoriteToggle: () -> Unit,
    onEditClick: () -> Unit,
    onDeleteClick: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            // 场景名称和收藏按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = scene.name,
                    style = MaterialTheme.typography.titleLarge,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    modifier = Modifier.weight(1f)
                )
                
                IconButton(onClick = onFavoriteToggle) {
                    Icon(
                        imageVector = if (scene.isFavorite) Icons.Filled.Star else Icons.Filled.StarBorder,
                        contentDescription = if (scene.isFavorite) "取消收藏" else "添加收藏",
                        tint = if (scene.isFavorite) MaterialTheme.colorScheme.tertiary else MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
            
            // 场景描述
            if (scene.description.isNotBlank()) {
                Text(
                    text = scene.description,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
                
                Spacer(modifier = Modifier.height(8.dp))
            }
            
            // 设备数量和操作按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "包含 ${scene.getDeviceIds().size} 个设备, ${scene.actions.size} 个动作",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                
                Spacer(modifier = Modifier.weight(1f))
                
                // 执行按钮
                IconButton(
                    onClick = onClick,
                    enabled = !isExecuting
                ) {
                    if (isExecuting) {
                        CircularProgressIndicator(
                            modifier = Modifier.width(24.dp),
                            strokeWidth = 2.dp
                        )
                    } else {
                        Icon(
                            imageVector = Icons.Default.PlayArrow,
                            contentDescription = "执行",
                            tint = MaterialTheme.colorScheme.primary
                        )
                    }
                }
                
                // 编辑按钮
                IconButton(onClick = onEditClick) {
                    Icon(
                        imageVector = Icons.Default.Edit,
                        contentDescription = "编辑",
                        tint = MaterialTheme.colorScheme.primary
                    )
                }
                
                // 删除按钮
                IconButton(onClick = onDeleteClick) {
                    Icon(
                        imageVector = Icons.Default.Delete,
                        contentDescription = "删除",
                        tint = MaterialTheme.colorScheme.error
                    )
                }
            }
        }
    }
} 